package com.korustar.autumnal.reflect;

import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Helper methods for inspecting fields
 * 
 * @author amir
 *
 */
public class StaticFieldReflection {
	private static final Logger LOGGER = LoggerFactory.getLogger(StaticFieldReflection.class);

	public static Class<?> getStaticFieldType(String staticField) {
		String enclosingType= getEnclosingType(staticField);
		String fieldname= getFieldnameFromStaticField(staticField);
		try {
			Class<?> enclosingClass = StaticFieldReflection.class.getClassLoader().loadClass(enclosingType);
			Field declaredField = enclosingClass.getDeclaredField(fieldname);
			return declaredField.getType();
		} catch(Exception ex) {
			LOGGER.warn("class/field not found on classpath",ex);
		}
		return null;
	}
	public static boolean isStaticFieldOnClasspath(String staticField) {
		String enclosingType= getEnclosingType(staticField);
		String fieldname= getFieldnameFromStaticField(staticField);
		try {
			Class<?> enclosingClass = StaticFieldReflection.class.getClassLoader().loadClass(enclosingType);
			//Field declaredField = 
				enclosingClass.getDeclaredField(fieldname);
			return true;
		} catch(Exception ex) {
			LOGGER.warn("class/field not found on classpath",ex);
		}
		return false;
	}
	

	private static String getEnclosingType(String staticField) {
		String enclosingType= staticField.substring(0, staticField.lastIndexOf('.'));
		return enclosingType;
	}

	public static String getFieldnameFromStaticField(String staticField) {
		String fieldName= staticField.substring(staticField.lastIndexOf('.')+1);
		return fieldName;
	}
}
